
var url = require('url');

var routes = {all: []};
var app = {};

var notFound = function(req, res){
	res.statusCode = 404;
	res.end(req.path + ' was not found');
};

var parseCookie = function(cookie)
{
	var cookies = {};
	if (!cookie)
	{
		return cookies;
	}

	var list = cookie.split(';');
	for (var i = 0; i < list.length; ++i)
	{
		var pair = list[i].split('=');
		cookies[pair[0].trim()] = pair[1];
	}

	return cookies;
}

app.use = function(path, action){
	routes.all.push([path, action]);
};

['get', 'post'].forEach(function(method){
	routes[method] = [];
	app[method] = function(path, action){
		routes[method].push([path, action]);
	};
});

app.run = function(req, res){
	var method = req.method.toLowerCase();
	var urlparts = url.parse(req.url, true);
	req.path = urlparts.pathname;
	req.query = urlparts.query;
	
	req.cookies = {};
	if (req.headers['Cookie'])
	{
		req.cookies = parseCookie(req.headers['Cookie']);
	}
	else if (req.headers['cookie'])
	{
		req.cookies = parseCookie(req.headers['cookie']);
	}

	/* all阶段的路由处理，可以完成权限检查之类的工作
	 * ret即表示该阶段的处理结果
	 */
	var ret = 0;
	for (var i = 0; i < routes.all.length; i++){
		if (routes.all[i][0] === req.path) {
			ret = routes.all[i][1](req, res);

			break;
		}
	}

	if (0 === ret && routes[method]){
		for (var i = 0; i < routes[method].length; i++){
			if (routes[method][i][0] === req.path){
				routes[method][i][1](req, res);
				return;
			}
		}
	}

	if (0 === ret)
	{
		notFound(req, res);
	}
};

module.exports = app;
